package dao.impl;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import bean.Type;
import common.util.DBUtils;
import common.util.UUIDUtils;
import dao.TypeDao;

public class TypeDaoImpl implements TypeDao {

	@Override
	public boolean insert(Type type) throws SQLException {
		Connection conn = DBUtils.getConnection();
		String sql = "insert into type values(?,?,?,?,?)";
		PreparedStatement pStatement = conn.prepareStatement(sql);
		pStatement.setString(1, UUIDUtils.getId());
		pStatement.setString(2, type.gettName());
		pStatement.setBigDecimal(3, type.gettTotal());
		pStatement.setBigDecimal(4, type.gettResidual());
		pStatement.setString(5, type.gettRemarks());
		//执行语句
		pStatement.executeUpdate();
		
		DBUtils.closeResource(conn, pStatement);
		//得到影响的行数，如果行数=1则执行成功
		int row = pStatement.getUpdateCount();
		return 1 == row ? true : false;
	}

	@Override
	public void deleteById(String id) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void update(Type t) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Type queryByid(String id) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Type> queryAll() throws SQLException {
		Connection conn = DBUtils.getConnection();
		String sql = "select * from type";
		PreparedStatement psmt = conn.prepareStatement(sql);
		ResultSet rs = psmt.executeQuery();
		List<Type> types = new ArrayList<>();
		while(rs.next()) {
			String typeId = rs.getString("typeId");
			String tName = rs.getString("tName");
			BigDecimal tTotal = rs.getBigDecimal("tTotal");
			BigDecimal tResidual = rs.getBigDecimal("tResidual");
			String tRemarks = rs.getString("tRemarks");
			Type type = new Type(typeId, tName, tTotal, tResidual, tRemarks);
			types.add(type);
		}
		DBUtils.closeResource(conn, psmt, rs);
		
		return types;
	}

}
